package com.csjy.migration.hnnd.business;

import com.csjy.migration.hnnd.*;
import com.csjy.migration.hnnd.annotation.BusinessDataConverter;
import com.csjy.migration.hnnd.dict.Bank;

import javax.script.ScriptException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@BusinessDataConverter(
    auto = false,
    insertSql = "INSERT INTO BPM_RESPONSIBILITY_REPAYMENT\n" +
        "(ID, CREATE_NAME, CREATE_BY, CREATE_DATE, UPDATE_NAME, UPDATE_BY, UPDATE_DATE, SYS_ORG_CODE, SYS_COMPANY_CODE, BPM_STATUS," +
        " PRO_ID, PRO_TYPE, REPAY_BANK, REPAYMENT_INTEREST_RATE, PLAN_REPAY, SHOULD_REPAYMENT_DATE, REPALY_MONEY, ACTUAL_REPAYMENT_DATE, CHECK_SIGN, " +
        " REPAY_VOUCHER, VOUCHER_FILE_ID, ACCOUNT_REMARK, CHECK_TIME, LOAN_ID, SUBSIDIES, IS_VALID, TASK_ID, PROC_ID, TASK_DEF_KEY, SOURCE_ID)\n" +
        " VALUES(?, ?, ?, ?, ?,?, ?, ?, ?, ?,?, ?, ?, ?, ?,?, ?, ?, ?, ?,?, ?, ?, ?, ?,?, ?, ?, ?, ?)\n",
    updateSql = "UPDATE BPM_RESPONSIBILITY_REPAYMENT\n" +
        "SET CREATE_NAME=?, CREATE_BY=?, CREATE_DATE=?, UPDATE_NAME=?, UPDATE_BY=?, UPDATE_DATE=?, SYS_ORG_CODE=?, SYS_COMPANY_CODE=?, BPM_STATUS=?, PRO_ID=?, PRO_TYPE=?, REPAY_BANK=?, REPAYMENT_INTEREST_RATE=?, PLAN_REPAY=?, SHOULD_REPAYMENT_DATE=?, REPALY_MONEY=?, ACTUAL_REPAYMENT_DATE=?, CHECK_SIGN=?, REPAY_VOUCHER=?, VOUCHER_FILE_ID=?, ACCOUNT_REMARK=?, CHECK_TIME=?, LOAN_ID=?, SUBSIDIES=?, IS_VALID=?, TASK_ID=?, PROC_ID=?, TASK_DEF_KEY=?, SOURCE_ID=?\n" +
        "WHERE ID = ?",
    findMigratedIdListSql = "SELECT ID FROM BPM_RESPONSIBILITY_REPAYMENT WHERE PROC_ID = ?"
)
public class BpmResponsibilityRepayment extends AbstractWorkflowBusiness {

  public BpmResponsibilityRepayment(DbUtil sourceDbUtil, DbUtil targetDbUtil, SourceBusinessData sourceData, ProgramArgument programArgument, String projectId, String procInstId) throws SQLException {
    super(sourceDbUtil, targetDbUtil, sourceData, programArgument, projectId, procInstId);
  }

  @Override
  public void migrate() throws Exception {
    List<Map> btItemAccountDetailList = this.sourceData.getBtItemAccountDetailList().stream()
        .filter(btItemAccountDetail->{
          String workflowNo = btItemAccountDetail.get("WORKFLOWNO") == null ? "" : btItemAccountDetail.get("WORKFLOWNO").toString();
          return workflowNo.equals(this.procInstId) && btItemAccountDetail.get("ACCOUNTTYPE").toString().equals("2");
        })
        .collect(Collectors.toList());
    for(Map.Entry<String,Map<String,Object>> entry : taskParamMap.entrySet()) {
      String curJbpmTaskInstanceId = entry.getKey();
      Map<String,Object> taskParam = entry.getValue();

      for (Map row : btItemAccountDetailList) {
        try {
          // 判断是否需要覆盖迁移
          int needMigratedResult = this.needMigrated(row.get("ACCOUNTNO").toString()+"-"+curJbpmTaskInstanceId);
          if(needMigratedResult == 0) {
            continue;
          }

          // 单条插入或更新
          if(needMigratedResult == 1) {
            this.targetDbUtil.updateByParams(updateSql,this.buildValues(row,curJbpmTaskInstanceId,taskParam),true);
            // 批量插入或更新 和 单条插入或更新 二选一
//            this.batchUpdateValues.add(this.buildValues(row, curJbpmTaskInstanceId, taskParam));
          } else {
            this.targetDbUtil.updateByParams(insertSql,this.buildValues(row, curJbpmTaskInstanceId, taskParam));
            // 批量插入或更新 和 单条插入或更新 二选一
//            this.batchInsertValues.add(this.buildValues(row, curJbpmTaskInstanceId, taskParam));
          }
        } catch(Exception e) {
          throw new Exception(String.format("流程实例[%s]-任务实例[%s]-还款数据迁移失败:%s\n",this.procInstId, curJbpmTaskInstanceId, e.getMessage()));
        }
      }
    }
  }

  public List buildValues(Map row, String curJbpmTaskInstanceId, Map<String,Object> taskParam) throws ScriptException, SQLException {
    List values = new ArrayList();
    // ID
    values.add(row.get("ACCOUNTNO")+"-"+curJbpmTaskInstanceId);
    // CREATE_NAME
    values.add(null);
    // CREATE_BY
    values.add(null);
    // CREATE_DATE
    values.add(row.get("CREATE_TIME"));
    // UPDATE_NAME
    values.add(null);
    // UPDATE_BY
    values.add(null);
    // UPDATE_DATE
    values.add(row.get("MODIFY_TIME"));
    // SYS_ORG_CODE
    values.add(null);
    // SYS_COMPANY_CODE
    values.add("002");
    // BPM_STATUS
    values.add(1);
    // PRO_ID 项目编号
    values.add(this.projectId);
    // PRO_TYPE 账目类型
    values.add(row.get("ACCOUNTTYPE"));
    //TODO: REPAY_BANK 还款银行 - 字典
    values.add(DictTool.getTargetDictCode(Bank.class,row.get("BANKID")));
    // REPAYMENT_INTEREST_RATE R还款月利率
    values.add(row.get("YEARRATE") == null ? row.get("MONTHRATE") : row.get("YEARRATE"));
    // PLAN_REPAY 还款计划
    values.add(row.get("PLANFLAG"));
    // SHOULD_REPAYMENT_DATE 应还日期
    values.add(row.get("SHOULDTIME"));
    // REPALY_MONEY 还款额 | 万
    values.add(row.get("OCCURSUM"));
    // ACTUAL_REPAYMENT_DATE 实还日期
    values.add(row.get("OCCURTIME"));
    // CHECK_SIGN 核实标记
    values.add(row.get("CHECKFLAG") == null ? BigDecimal.valueOf(0): ((BigDecimal)row.get("CHECKFLAG")).subtract(BigDecimal.ONE));
    // REPAY_VOUCHER 还款凭证
    values.add(row.get("ELEFILENAME") );
    // VOUCHER_FILE_ID 凭证文件ID
    values.add(row.get("ELEFILESTORENAME") == null ? null : row.get("ELEFILESTORENAME").toString().replace("-",""));
    // ACCOUNT_REMARK 账目备注
    String accountRemark = row.get("ACCOUNTMEMO") == null ? "" : Tool.decodeUnicode(row.get("ACCOUNTMEMO").toString());
    accountRemark = accountRemark
        +"\n\n老系统其他字段信息"
        + "\n还款方式："+ row.get("RETURNWAY") + "-" + BusinessTool.getOldDictDataNameByDictCodeAndDataCode("35",row.get("RETURNWAY"))
        + " \n还款计划："+ row.get("PLANFLAG") + "-" + BusinessTool.getOldDictDataNameByDictCodeAndDataCode("46",row.get("PLANFLAG"))
        + " \n还款月利率："+ row.get("MONTHRATE");

    values.add(accountRemark);
    // CHECK_TIME 复核时间
    values.add(row.get("CHECKTIME"));
    // LOAN_ID 放款编号
    values.add(row.get("LOANACCOUNTNO"));
    // TODO:SUBSIDIES 申请利息标记
    values.add(null);
    //  IS_VALID	是否使用
    values.add("Y");
    //  TASK_ID	任务ID
    values.add(curJbpmTaskInstanceId + "-JW");
    //  PROC_ID	流程ID
    values.add(this.procInstId + "-JW");
    //  TASK_DEF_KEY	节点ID
    values.add(taskParam.get("taskDefKey"));
    //  SOURCE_ID		业务ID
    values.add(row.get("ACCOUNTNO"));
    return values;
  }

}
